﻿using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using MinimalistFoodStreet.BackEnd.Api.Api.Controllers;
using MinimalistFoodStreet.BackEnd.Infrastructure.Attributes;
using MinimalistFoodStreet.BackEnd.Server.IServer;
using System.Reflection;
using Microsoft.AspNetCore.Http.HttpResults;

namespace MinimalistFoodStreet.BackEnd.Api.Api.Filters
{
    public class CheckLoginFilter : IActionFilter
    {
        private readonly IConfiguration _configuration;
        private readonly ILoginServer _loginServer;

        public CheckLoginFilter(IConfiguration configuration, ILoginServer loginServer)
        {
            _configuration = configuration;
            _loginServer = loginServer;
        }

        public void OnActionExecuted(ActionExecutedContext context)
        {
        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            var action = context.ActionDescriptor as ControllerActionDescriptor;
            if (action == null)
                return; // 非控制器动作，无需处理

            // 检查方法或控制器是否包含CheckLogin特性
            var methodAttr = action.MethodInfo.GetCustomAttribute<CheckLoginAttribute>();
            var controllerAttr = action.ControllerTypeInfo.GetCustomAttribute<CheckLoginAttribute>();

            if (methodAttr == null && controllerAttr == null)
                return; // 无需检查

            // 执行登录检查逻辑
            // 创建工具实例
            var jwtHelper = new JwtHelper(_configuration);
            // 解析Token
            string token = context.HttpContext.Request.Headers["Authorization"];
            if (string.IsNullOrEmpty(token) || token.Length <= 7 || !token.StartsWith("Bearer "))
            {
                context.Result = new UnauthorizedResult(); return;
            }
            token = token.Substring(7);
            UserPayload parsedUser = null;
            try
            {
                parsedUser = jwtHelper.ParseToken<UserPayload>(token);
            }
            catch
            {
                context.Result = new UnauthorizedResult(); return;
            }
            if (parsedUser == null)
            {
                context.Result = new UnauthorizedResult(); return;
            }
            // 检查用户是否登录
            var account = _loginServer.CheckLogin(Convert.ToInt32(parsedUser.id), parsedUser.code);
            if (account == null || account.AIsBan == 1)
            {
                context.Result = new UnauthorizedResult(); return;
            }
            CheckLoginRoles parsedRole;
            // 验证用户的角色被允许
            if ((!Enum.TryParse(account.AEndpoint, out parsedRole)) || (!(controllerAttr == null ? methodAttr : controllerAttr).AllowedRoles.Contains(parsedRole)))
            {
                context.Result = new UnauthorizedResult(); return;
            }
            // 将用户对象存储到控制器全局对象
            if (context.Controller is BaseController controller)
            {
                controller._account = account;
                // 根据实际类型进行转换
                switch (account.AEndpoint)
                {
                    case "administrators":
                        controller._administrator = _loginServer.GetAdministrator(account.AId); break;
                    case "suppliers":
                        controller._supplier = _loginServer.GetSupplier(account.AId); break;
                    case "business":
                        controller._business = _loginServer.GetBusiness(account.AId); break;
                }
            }
        }
    }
}
